package com.campus.common;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.campus.domain.Dto.StudentBatchAddDto;
import com.campus.domain.Vo.StudentExamineBatchVo;
import com.campus.service.IStudentService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class StudentBatchExamineListener implements ReadListener<StudentExamineBatchVo> {
    /**
     * 每次读取的最多行数
     */
    private static final int MAX_ROW_PER_READ = 5 ;
    /**
     * 利用studentDao将读取到的数据，批量存入数据库。
     */
    private IStudentService studentService ;
    /**
     * 存储读取到的数据
     */
    private List<StudentExamineBatchVo> cachedReadData = ListUtils.newArrayListWithExpectedSize(MAX_ROW_PER_READ) ;

    public StudentBatchExamineListener(IStudentService studentService) {
        this.studentService = studentService ;
    }
    /**
     * 每次easyexcel读取到一行数据，都会调用该方法
     * @param studentExamineBatchVo
     * @param analysisContext
     */

    @Override
    public void invoke(StudentExamineBatchVo studentExamineBatchVo, AnalysisContext analysisContext) {
        log.info("读取到一条学生信息：{}", studentExamineBatchVo) ;
        cachedReadData.add(studentExamineBatchVo) ;
        if (cachedReadData.size() >= MAX_ROW_PER_READ) {

            // 达到每行最大读取数，需要将数据写入数据库
            log.info("数据写入数据库：{}", cachedReadData);
            studentService.examineStudentBatch(cachedReadData);
            // 清空缓存数据
            cachedReadData = ListUtils.newArrayListWithExpectedSize(MAX_ROW_PER_READ) ;

        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 所有数据读取完毕，需要将剩余的数据写入数据库
        log.info("数据写入数据库：{}", cachedReadData) ;
        studentService.examineStudentBatch(cachedReadData);
        log.info("读取完毕");
    }
}
